package com.shiguiwu.springboot3.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shiguiwu.springboot3.util.JwtUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.security.SignatureException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {


    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    JwtUtils jwtUtils;
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        
        String errorMessage = "";
        String authHeader = request.getHeader("Authorization");
        
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            errorMessage = "缺少有效的Access Token";
        } else {
            try {
                // 尝试解析Token获取具体错误
                String token = authHeader.substring(7);
                jwtUtils.validateToken(token);

                //errorMessage = "Token验证失败";
            } catch (ExpiredJwtException e) {
                errorMessage = "Access Token已过期，请使用Refresh Token刷新";
                response.setHeader("X-Token-Expired", "true");
            } catch (MalformedJwtException e) {
                errorMessage = "Token格式无效";
            } catch (SignatureException e) {
                errorMessage = "Token签名验证失败";
            } catch (Exception e) {
                errorMessage = "Token验证失败";
            }
        }
        
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("error", "unauthorized");
        errorResponse.put("message", errorMessage);
        errorResponse.put("path", request.getServletPath());
        
        response.getWriter().write(objectMapper.writeValueAsString(errorResponse));
    }
}